package com.ophiux.cs.application.consultBase.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ophiux.cs.application.consultBase.dto.AddDeptRequest;
import com.ophiux.cs.application.consultBase.dto.AddDeptResponse;
import com.ophiux.cs.application.consultBase.service.IAddDeptAppService;
import com.ophiux.cs.application.core.Result;
import com.ophiux.cs.application.core.ResultEnum;
import com.ophiux.cs.domain.consultBase.model.entity.Dept;
import com.ophiux.cs.domain.consultBase.repositories.IDeptRepository;
import com.ophiux.utils.common.RandomUtil;
import com.ophiux.utils.common.ShiftUtils;
import com.ophiux.utils.exception.OphiuxRepositoryException;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class AddDeptAppService implements IAddDeptAppService {

    @Autowired
    IDeptRepository deptRepositories;

    @Override
    public Result<AddDeptResponse> createDept(AddDeptRequest dto) {
        AddDeptResponse resp = new AddDeptResponse();
        //验证参数是否允许为空
        if (!dto.isParamValid()) {
            return Result.fail(ResultEnum.requestParamFail.getCode(), ResultEnum.requestParamFail.getMsg());
        }
        try {
            Dept dept = null;
            dept = (Dept) ShiftUtils.objToNewObj(dto, Dept.class);
            try {
                boolean flag=true;
                String deptID="";
                //生成科室编码
                while(flag){
                    //随机生成6位数
                    deptID=RandomUtil.getRandomNum(6);
                    Dept dt=deptRepositories.getDeptByID(deptID);
                    if(dt==null){
                        dept.setDEPT_ID(deptID);
                        flag=false;
                    }
                }
                //开始新增科室，若科室存在则更新
                 deptRepositories.createDept(dept);
                resp.setDEPT_ID(dept.getDEPT_ID());
            } catch (OphiuxRepositoryException e) {
                e.printStackTrace();
                return Result.fail(ResultEnum.requestException.getCode(), e.getExceptionMessage());
            }
        } catch (Exception e) {
            log.info("createDept接口异常：", e);
            e.printStackTrace();
            return Result.fail(ResultEnum.requestException.getCode(), ResultEnum.requestException.getMsg());
        }
        return Result.success(resp, "新增科室成功");
    }

}
